/**
 * Construct a row database object.  Keeps track of the rows we are displaying
 * locally so we can perform interesting operations on them.
 */
function RowDb() {
  this.rows = new Array();

  /*
   * Create a new row and add it to the list for this page.
   */
  this.newRow = function(id, title, isWritelyDoc, taglist, actions) {
    var row = new Row(id, title, isWritelyDoc, taglist, actions);

    this.rows.push(row);

    return row;
  };


  /**
   * Return the N'th row object
   */
  this.getRow = function(index) {
    if (index >= this.rows.length) {
      return null;
    } else {
      return this.rows[index];
    }
  };

  /**
   * Return the set of all tags for all documents in the list.  Bad
   * implementation for now.
   */
  this.getAllTags = function() {
    var result = new Array();

    for (var i = 0; i < this.rows.length; i++) {
      var row = this.getRow(i);
      var tags = row.getTagList();

      for (var j = 0; j < tags.length; j++) {
        addUnique(result, tags[j]);
      }
    }

    result.sort();

    return result;
  };

  this.format = function() {
    var result = "";

    for (var i = 0; i < this.rows.length; i++) {
      result += this.getRow(i).format();
    }

    return result;
  }
}

/**
 * Construct a new row object
 */
function Row(id, name, isWritely, tagList, actions) {
  this.id = id;
  this.name = name;
  this.actions = actions;
  this.isWritely = isWritely;
  this.tagList = new Array();

  var tags = tagList.split(",");

  for (var i = 0; i < tags.length; i++) {
    if (tags[i].length > 0) {
      addUnique(this.tagList, tags[i]);
    }
  }

  this.getId = function() {
    return this.id;
  };

  this.getName = function() {
    return this.name;
  };

  this.isWritelyDoc = function() {
    return this.isWritely;
  };

  this.getTagList = function() {
    return this.tagList;
  };

  this.format = function() {
    var s = "row(" + this.getId() + ")";
    return s;
  };
}

/**
 * Add the specified entry to the end of the list if it is not already in
 * the list
 */
function addUnique(list, entry) {
  for (var i = 0; i < list.length; i++) {
    if (list[i] == entry) {
      return;
    }
  }

  list.push(entry);
}
